<template>
    <div>
        <el-tabs v-model="searchForm.tab" @tab-change="getData">
            <el-tab-pane v-for="(item,index) in tabbars" :key="index" :label="item.name" :name="item.key">
            </el-tab-pane>
        </el-tabs>

        <el-card class="border-0">
            <Search :model="searchForm" @search="getData" @reset="resetSearchForm">
                <!-- 初始展示区域 -->
                <SearchItem label="关键词">
                    <el-input v-model="searchForm.title" placeholder="商品名称" clearable></el-input>
                </SearchItem>
                <!-- 展开收起控制区域 -->
                <template #show>
                    <SearchItem label="收货人">
                        <el-input v-model="searchForm.name" placeholder="收货人"></el-input>
                    </SearchItem>
                    <SearchItem label="手机号">
                        <el-input v-model="searchForm.phone" placeholder="手机号"></el-input>
                    </SearchItem>
                    <SearchItem label="开始时间">
                        <el-date-picker v-model="searchForm.starttime" type="date" placeholder="开始日期" :default-value="new Date()" />
                    </SearchItem>
                    <SearchItem label="结束时间">
                        <el-date-picker v-model="searchForm.endtime" type="date" placeholder="结束时间" :default-value="new Date()" />
                    </SearchItem>
                </template>
            </Search>

            <!-- 新增|刷新 -->
            <ListHeader layout="refresh,download" @refresh="getData" @download="handleExportExcel">
                <el-button type="danger" size="small" @click="handleMult" v-if="searchForm.tab !== 'delete'">批量删除</el-button>
            </ListHeader>

            <el-table :data="tableData" stripe style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="80" />
                <el-table-column label="商品" width="400">
                    <template #default="{ row }">
                        <div class="flex">
                            <div>
                                <div>订单号</div>
                                {{ row.no }}
                            </div>
                            <div class="ml-15">
                                <div>下单时间</div>
                                {{ row.create_time }}
                            </div>
                        </div>
                        <div>
                            <div v-for="(item,index) in row.order_items" :key="item.id" class="flex ml-2 mt-3" style="align-items:center">
                                <el-image :src="item.goods_item ? item.goods_item.cover :''" fit="fill" :lazy="true" style="width:40px;height:40px"></el-image>
                                <span class="text-blue-600">{{item.goods_item?.title }}</span>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="实付款" prop="total_price" width="80" align="center" />
                <el-table-column label="买家" width="100" align="center">
                    <template #default="{row}">
                        <p>{{ row.user.username || row.user.nickname}}</p>
                        <p>(用户ID: {{row.user.id ? row.user.id : ''}})</p>
                    </template>
                </el-table-column>
                <el-table-column label="交易信息" width="200">
                    <template #default="{ row }">
                        <div>
                            付款状态：
                            <el-tag v-if="row.payment_method == 'wechat'" type="success" size="small">微信支付</el-tag>
                            <el-tag v-else-if="row.payment_method == 'alipay'" size="small">支付宝支付</el-tag>
                            <el-tag v-else type="info" size="small">未支付</el-tag>
                        </div>
                        <div>
                            发货状态：
                            <el-tag :type="row.ship_data ? 'success' : 'info'" size="small">{{ row.ship_data ? '已发货' : '未发货' }}</el-tag>
                        </div>
                        <div>
                            收货状态：
                            <el-tag :type="row.ship_status == 'received' ? 'success' : 'info'" size="small">{{ row.ship_status == 'received' ? '已收货' : '未收货' }}</el-tag>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template #default="{row}">
                        <el-button class="px-1" type="primary" size="small" text @click="handleOrderDetail(row)">订单详情</el-button>
                        <el-button v-if="searchForm.tab === 'noship' || (searchForm.tab === 'all' && row.payment_method !== null)" class="px-1" type="primary" size="small" text @click="handleShipOrder(row)">订单发货</el-button>
                        <el-button v-if="searchForm.tab === 'refunding'" class="px-1" type="primary" size="small" text @click="handleRefund(row)">同意退款</el-button>
                        <el-button v-if="searchForm.tab === 'refunding'" class="px-1" type="primary" size="small" text @click="openDialog(row,0)">拒绝退款</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="flex items-center justify-center mt-5">
                <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage" :page-size="limit" @current-change="getData" />
            </div>

            <FormDrawer destroyOnClose ref="formDrawerRef" title="订单发货" @submit="handleSubmit">
                <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
                    <el-form-item label="快递公司" prop="express_company">
                        <el-select v-model="form.express_company" placeholder="请选择快递公司" clearable>
                            <el-option v-for="item in expressCompanyList" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="快递单号" prop="express_no">
                        <el-input v-model="form.express_no" placeholder="请输入快读单号" style="width:80%"></el-input>
                    </el-form-item>
                </el-form>
            </FormDrawer>
            <!-- 拒绝退款理由弹出框 -->
            <el-dialog v-model="dialogVisible" title="Tips" width="30%" align-center>
                <el-input v-model="obj.disagree_reason" placeholder="请输入拒绝理由"></el-input>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="handleRefundOrder" :loading="loading">
                            确认
                        </el-button>
                    </span>
                </template>
            </el-dialog>

            <ExportExcel :tabs="tabbars" ref="ExportExcelRef" />

            <OrderDetail ref="OrderDetailRef" :tab="searchForm.tab" />
        </el-card>
    </div>
</template>
<script setup>
import { ref } from "vue"
import ExportExcel from './components/ExportExcel.vue'
import OrderDetail from './components/orderDetail.vue'
import Search from '~/components/Search.vue'
import SearchItem from "~/components/SearchItem.vue";
import FormDrawer from "~/components/FormDrawer.vue";
import ListHeader from "~/components/ListHeader.vue";
import {
    getOrderList,
    deleteOrderList,
    getexpressCompanyList,
    shipOrderList,
    refundOrder,
    excelexportOrder
} from "~/api/order.js"
import { toast } from '~/composables/util.js'
import { useInitTable, useInitForm } from "~/composables/useCommon";
import { ElMessageBox } from 'element-plus'

const { searchForm,
    resetSearchForm,
    tableData,
    loading,
    currentPage,
    total,
    limit,
    getData,
    handleDelete,
    handleSelectionChange,
    handleMult,
    handleMultiStatusChange,
    multiSelectionIds,
    multipleTableRef } = useInitTable({
        searchForm: {
            tab: 'all',
            no: '',
            starttime: '',
            endtime: '',
            name: '',
            phone: '',
        },
        getList: getOrderList,
        delete: deleteOrderList,
    })

const { formDrawerRef,
    formRef,
    form,
    rules,
    drawerTitle,
    handleCreate,
    handleEdit } = useInitForm(
        {
            form: {
                express_company: '',
                express_no: ''
            },
        })
// 定义标签
const tabbars = [
    {
        key: 'all',
        name: '全部'
    },
    {
        key: 'nopay',
        name: '待付款'
    }, {
        key: 'noship',
        name: '待发货'
    }, {
        key: 'shiped',
        name: '待收货'
    }, {
        key: 'received',
        name: '已收货'
    }, {
        key: 'finish',
        name: '已完成'
    }, {
        key: 'closed',
        name: '已关闭'
    }, {
        key: 'refunding',
        name: '退款中'
    }

]

const OrderDetailRef = ref(null)
const handleOrderDetail = (row) => {
    OrderDetailRef.value.open(row)
}

const orderId = ref(0)

const expressCompanyList = ref([])
getexpressCompanyList().then(res => {
    console.log(res);
    expressCompanyList.value = res.list
})

// 表单提交执行的方法
const handleSubmit = () => {
    formDrawerRef.value.showLoading()
    shipOrderList(orderId.value, form).then(res => {
        console.log(res);
    }).finally(() => {
        formDrawerRef.value.hideLoading()
    })
}
// 打开弹出框，并保存id
const handleShipOrder = (item) => {
    orderId.value = item.id
    formDrawerRef.value.open()
}

let obj = ref({
    agree: 1,
    disagree_reason: ''
})
// 控制对话框的显示与隐藏
let dialogVisible = ref(false)
// 拒绝理由
let refuse = ref('')
const openDialog = (item, type) => {
    obj.value.agree = type
    orderId.value = item.id
    dialogVisible.value = true
}
// 同意退款的回调
const handleRefund = (item) => {
    ElMessageBox.confirm(
        '是否要同意该订单退款?',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            refundOrder(item.id, obj.value).then(res => {
                console.log(res);
            })
        })
        .catch(() => {

        })
}

// 拒绝发送的请求
const handleRefundOrder = () => {
    if (obj.value.disagree_reason == '' && obj.value.agree == 0) {
        return toast('拒绝理由不能为空', 'warning')
    }
    dialogVisible.value = false
    loading.value = true
    refundOrder(orderId.value, obj.value).then(res => {
        toast('拒绝成功')
    }).finally(() => {
        loading.value = false
    })
}

// 导出按钮触发的事件
const ExportExcelRef = ref(null)
const handleExportExcel = () => {
    ExportExcelRef.value.open()
}
</script>